package io.jee.medusa.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.CRC32;

import org.apache.commons.codec.binary.Hex;

public class FileUtils {
	
	public static void removes(String path, long beforeTime){
		File dir = new File(path);
		if(dir.exists()){
			File[] childFiles = dir.listFiles();
			if(childFiles==null){
				dir.delete();
			}else{
				for (File file : childFiles) {
					if(file.isDirectory()){
						removes(file.getPath(), beforeTime);
					}else{
						if(file.lastModified()<beforeTime){
							file.delete();
						}
					}
				}
			}
		}
	}
	
	public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
 
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else
            return String.format("%d B", size);
    }
	
    public static String getExtensionName(String filename) { 
        if ((filename != null) && (filename.length() > 0)) { 
            int dot = filename.lastIndexOf('.'); 
            if ((dot >-1) && (dot < (filename.length() - 1))) { 
                return filename.substring(dot + 1); 
            } 
        } 
        return null; 
    } 

    public static String getFileNameNoEx(String filename) { 
        if ((filename != null) && (filename.length() > 0)) { 
            int dot = filename.lastIndexOf('.'); 
            if ((dot >-1) && (dot < (filename.length()))) { 
                return filename.substring(0, dot); 
            } 
        } 
        return null; 
    }
	
	public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchAlgorithmException {
//		File file = new File("F:/迅雷下载/SW_DVD5_Office_Professional_Plus_2013_64Bit_ChnSimp_MLF_X18-55285.ISO");
//		long ddd = System.currentTimeMillis();
//		System.out.println(FileUtils.updateDigest(new FileInputStream(file)));
//		System.out.println(System.currentTimeMillis()-ddd);
		removes("d:/cdn/logs", 100022l);
	}
	
	private static final int STREAM_BUFFER_LENGTH = 10240;
	
	public static String sha256Hex(final InputStream data){
		try {
			return Hex.encodeHexString(updateDigest("SHA-256", data).digest());
		} catch (NoSuchAlgorithmException | IOException e) {
			return null;
		}
	}
	
	public static String crc32(final InputStream data){
		CRC32 crc32 = new CRC32();
		final byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
		try{
			int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);

	        while (read > -1) {
	        	crc32.update(buffer, 0, read);
	            read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
	        }
		}catch(Exception e){
			return null;
		}
        return Long.toHexString(crc32.getValue()).toLowerCase();
	}
	
    public static MessageDigest updateDigest(final String algorithm, final InputStream data) throws IOException, NoSuchAlgorithmException {
    	MessageDigest digest = MessageDigest.getInstance(algorithm);
    	
    	final byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
        int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);

        while (read > -1) {
            digest.update(buffer, 0, read);
            read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
        }

        return digest;
    }
    
    public static Digest updateDigest(final InputStream data) throws IOException, NoSuchAlgorithmException {
    	MessageDigest md5 = MessageDigest.getInstance("md5");
    	MessageDigest sha1 = MessageDigest.getInstance("SHA");
    	MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
    	CRC32 crc32 = new CRC32();
    	
    	final byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
        int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
        while (read > -1) {
        	md5.update(buffer, 0, read);
        	sha1.update(buffer, 0, read);
        	sha256.update(buffer, 0, read);
        	crc32.update(buffer, 0, read);
            read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
        }
        Digest digest = new FileUtils().new Digest();
        digest.setMd5(Hex.encodeHexString(md5.digest()));
        digest.setSha1(Hex.encodeHexString(sha1.digest()));
        digest.setSha256(Hex.encodeHexString(sha256.digest()));
        digest.setCrc32(Long.toHexString(crc32.getValue()));
        return digest;
    }
    

    public class Digest {
    	private String md5;
    	private String sha1;
    	private String sha256;
    	private String crc32;
    	
		public String getMd5() {
			return md5;
		}
		public void setMd5(String md5) {
			this.md5 = md5;
		}
		public String getSha1() {
			return sha1;
		}
		public void setSha1(String sha1) {
			this.sha1 = sha1;
		}
		public String getSha256() {
			return sha256;
		}
		public void setSha256(String sha256) {
			this.sha256 = sha256;
		}
		public String getCrc32() {
			return crc32;
		}
		public void setCrc32(String crc32) {
			this.crc32 = crc32;
		}
		
		@Override
		public String toString() {
			return "Digest [md5=" + md5 + ", sha1=" + sha1 + ", sha256=" + sha256 + ", crc32=" + crc32 + "]";
		}
    	
    }

}
